//
//  PersonViewController.m
//  HeSaid
//
//  Created by MWJ on 15/5/4.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "PersonViewController.h"
#import "AppDelegate.h"
#import "DataCell.h"    //个人资料的cell
#import "SetUpViewController.h"
#import "PostDetailViewController.h"
#import "personPost.h"
#import "ViewController.h"
#import "SDRefresh.h"
#define personalDataURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/PersonalCenter" //个人资料URL
#define personalpostURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/PersonalCenterPost"//个人帖子URL
#define allPostURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/PersonalCenterPostAll"//全部帖子URL


@interface PersonViewController (){
    NSMutableArray *personArray;
    NSMutableArray *personPostArray;
    NSMutableArray *postArray;
    AppDelegate *app;
    NSString *messageId;
}

@property (nonatomic, weak) SDRefreshFooterView *refreshFooter;


@end

@implementation PersonViewController
-(void)viewWillAppear:(BOOL)animated{
    self.view.backgroundColor = [UIColor whiteColor];
<<<<<<< HEAD
    [app isConnectionAvailable];
    if ([app.Existence isEqualToString:@"1"]) {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"当前网络不可用，请检查网络连接！"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }else{
    }
=======
        [app isConnectionAvailable];
        if ([app.Existence isEqualToString:@"1"]) {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"当前网络不可用，请检查网络连接！"delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }else{
        }
>>>>>>> 4b04801d95a25eb22fcb8820da68a35773c3052f
}
- (void)viewDidLoad {
    [super viewDidLoad];
    app=(AppDelegate *)[[UIApplication sharedApplication]delegate];
    [app.defaults setObject:app.user_id forKey:@"yonghu"];
    [app.defaults synchronize];
    self.headPortrait.layer.masksToBounds = YES;
    self.headPortrait.layer.cornerRadius = self.headPortrait.bounds.size.width/2;
    self.navigationItem.hidesBackButton=YES;
    personArray = [NSMutableArray array];
    postArray = [NSMutableArray array];
    self.view.backgroundColor = [UIColor clearColor];
    self.navigationItem.title=@"个人中心";
    
    //创建“设置按钮”
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"03.png"] style:UIBarButtonItemStylePlain target:self action:@selector(rightItemClick)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    //创建回到首页
        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed: @"04.png"] style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClick)];
        self.navigationItem.leftBarButtonItem = leftItem;
    //调用加载个人信息方法
    NSString *poststr =[NSString stringWithFormat:@"user_id=%@",app.user_id];
    [self londingPath:personalDataURL Str:poststr];
    //调用加载帖子列表方法
    NSString *poststr1 =[NSString stringWithFormat:@"user_id=%@",app.user_id];
    [self londingPath1:personalpostURL Str1:poststr1];
    
    //上拉加载
    [self setupFooter];
}

#pragma mark - 上拉加载
- (void)setupFooter
{
    SDRefreshFooterView *refreshFooter = [SDRefreshFooterView refreshView];
    [refreshFooter addToScrollView:self.personTableView];
    [refreshFooter addTarget:self refreshAction:@selector(footerRefresh)];
    _refreshFooter = refreshFooter;
}


- (void)footerRefresh
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        postArray=[NSMutableArray array];
        NSString *poststr =[NSString stringWithFormat:@"id=%@",app.user_id];
        [self londingPath1:allPostURL Str1:poststr];
        [self.personTableView reloadData];
        [self.refreshFooter endRefreshing];
        
    });
}


#pragma mark - 导航栏左边按钮点击事件
-(void)leftItemClick{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ViewController *VC = [storyboard instantiateViewControllerWithIdentifier:@"viewVC"];
    [self.navigationController pushViewController:VC animated:YES];
}
#pragma mark - 加载个人信息，头像，性别，号码，积分
-(void)londingPath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSArray *array = [NSArray array];
        array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:array waitUntilDone:YES];
    }];
}
- (void)refreshData:(NSArray *)sender{
    self.phoneLabel.text = sender[0][@"user_phone"];
    app.user_phone = self.phoneLabel.text;
    self.sexLabel.text = sender[0][@"user_sex"];
    app.user_sex = self.sexLabel.text;
    self.integralLabel.text = sender[0][@"user_count"];
    //积分数
    app.integralCount=self.integralLabel.text;
    //头像
    NSString *headportrait = [NSString stringWithFormat:@"%@",sender[0][@"user_HeadPortrait"]];
    NSURL *url=[NSURL URLWithString:headportrait];
    self.headPortrait.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
}
#pragma mark - 请求帖子列表数据
-(void)londingPath1:(NSString *)path Str1:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        personPostArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData1:) withObject:personPostArray waitUntilDone:YES];
    }];
}
-(void)refreshData1:(NSMutableArray *)sender1{
    for (NSDictionary *dic in sender1) {
        personPost *p = [[personPost alloc]init];
        p.postcontent = dic[@"message_content"];
        p.postreply = dic[@"message_Comment"];
        p.posttime = dic[@"message_time"];
        p.postshowtime = dic[@"message_showtime"];
        p.message_id=dic[@"message_id"];
        [postArray addObject:p];
    }
    [self.personTableView reloadData];
    
}
#pragma mark - 导航栏右边按钮点击事件
-(void)rightItemClick{
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    SetUpViewController *setUp = [storyboard instantiateViewControllerWithIdentifier:@"setUpVC"];
    [self.navigationController pushViewController:setUp animated:YES];
}

#pragma  mark - cell的个数

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return postArray.count;
}

#pragma  mark - 每一行cell的高度

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 115;
}

#pragma  mark - cell的内容

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UINib *nib=[UINib nibWithNibName:@"DataCell" bundle:nil];
    [self.personTableView registerNib:nib forCellReuseIdentifier:@"data"];
    
    static NSString *cellIdentifier=@"data";
    DataCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    personPost *pp = postArray[indexPath.row];

    cell.time.text = [NSString stringWithFormat:@"%@",pp.posttime];
    cell.reply.text=[NSString stringWithFormat:@"%@",pp.postreply];
    cell.content.text=[NSString stringWithFormat:@"%@",pp.postcontent];
    cell.ShowTime.text=[NSString stringWithFormat:@"%@",pp.postshowtime];
    cell.messageID = [NSString stringWithFormat:@"%@",pp.message_id];
    cell.messagecontent = [NSString stringWithFormat:@"%@",pp.postcontent];
    cell.messageshowtime = [NSString stringWithFormat:@"%@",pp.postshowtime];
    app.message_id=cell.messageID;
    cell.messagecomment = [NSString stringWithFormat:@"%@",pp.postreply];
    
    return cell;
}

#pragma  mark - cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    personPost *pp = postArray[indexPath.row];
    app.message_id = [NSString stringWithFormat:@"%@",pp.message_id];
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    PostDetailViewController *postDetail = [storyboard instantiateViewControllerWithIdentifier:@"postDetailVC"];
    [self.navigationController pushViewController:postDetail animated:YES];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
